﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using System.IO;
using System.IO.Ports;
using System.Text.RegularExpressions;  
namespace ButtonCreate
{
    public partial class Form1 :  Skin_DevExpress
    {
        //ports
        private bool _closing; //是否正在关闭串口，执行Application.DoEvents，并阻止再次
        private bool _listening; //是否没有执行完invoke相关操作  
        public Dictionary<string, List<byte>> button_dictionary = new Dictionary<string, List<byte>>();

        public Form1()
        {
            InitializeComponent();
            serialportcheck();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        #region 加载文件
        private void skinButton1_Click(object sender, EventArgs e)
        {
            int button_count_total = 0;
            int button_count = 0;
            OpenFileDialog ofd = new OpenFileDialog();
            //设置打开对话框的标题
            ofd.Title = "请选择协议文件文件";
            //设置打开对话框可以多选
            ofd.Multiselect = true;
            //设置对话框打开的文件类型
            ofd.Filter = "文本文件|*.txt";
            //设置文件对话框当前选定的筛选器的索引
            ofd.FilterIndex = 2;
            //设置对话框是否记忆之前打开的目录
           // ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                button_dictionary.Clear();
                skinPanel1.Controls.Clear();

                //获取用户选择的文件完整路径
                string filePath = ofd.FileName;
                //获取对话框中所选文件的文件名和扩展名，文件名不包括路径
                string fileName = ofd.SafeFileName;
                //获取按键总数
                button_count_total = Get_Rows(filePath);
                label6.Text = fileName;

                if (button_count_total > 52)
                {
                    MessageBox.Show("超过了最大数量52！");
                    return;
                }

                string line_string = "";
                using (StreamReader read = new StreamReader(filePath, Encoding.Default))
                {
                    while ((line_string =read.ReadLine()) != null)
                    {                      
                        try
                        {
                            button_dictionary.Add(button_count.ToString(), Get_HexBuffer(Get_Cmd_Buffer(line_string)));
                        }
                        catch
                        {
                            MessageBox.Show("请检查数据格式！");
                            return;
                        }

                        try
                        {
                            Create_Buttons(button_count, Get_Cmd_Name(line_string));
                        }

                        catch
                        {
                            continue;
                        }
                     
                        button_count++;                       
                    }
                }
                
            }


        }
        #endregion

        #region  读取文件行数
        private int Get_Rows(string file_path)
        {
            using (StreamReader read = new StreamReader(file_path, Encoding.Default))
            {
                return read.ReadToEnd().Split('\n').Length;
            }
        }
        #endregion
        
        #region  生成按键
        private void Create_Buttons(int button_count,string button_name)
        {
            int row = 0;
            row = button_count / 4;
            CCWin.SkinControl.SkinButton btn = new CCWin.SkinControl.SkinButton();
            btn.BackColor = System.Drawing.SystemColors.HotTrack;
            btn.BaseColor = System.Drawing.SystemColors.HotTrack;
            btn.BorderColor = System.Drawing.Color.Cyan;
            btn.ControlState = CCWin.SkinClass.ControlState.Normal;
            btn.TabIndex = 1;           
            btn.UseVisualStyleBackColor = true;
            btn.ForeColor = System.Drawing.SystemColors.Menu;
            btn.Click += new System.EventHandler(Button_Click);
            //控件名称
            btn.Name = button_count.ToString();

            //控件显示文本
            btn.Text = button_name;

            //控件大小
            btn.Size = new Size(82,30);

            //控件位置【动态变化】
            btn.Location = new Point(20 + button_count % 4 * (5 + 87), 20 + row * (10 + 30));

            //添加到窗体
            skinPanel1.Controls.Add(btn);
        }
        #endregion

        #region  字符串截取
        private string Get_Cmd_Name(string souce_str)
        {
            int i = souce_str.IndexOf('：');          
            string return_string = "";
            return_string = souce_str.Substring(0, i);
            return return_string;
        }

        private string Get_Cmd_Buffer(string souce_str)
        {
            int i = souce_str.IndexOf('：');
            string return_string = "";
            return_string = souce_str.Substring(i + 1, souce_str.Length - i - 1);
            return return_string;
        }

        #endregion

        #region  按键事件
        private void Button_Click(object sender, EventArgs e)
        {
            CCWin.SkinControl.SkinButton pb = sender as CCWin.SkinControl.SkinButton;
            string key = pb.Name;

            if (button_dictionary.Keys.Contains(pb.Name))
            {
                Data_Send(button_dictionary[key]);
            }
        }
        #endregion

        #region  串口控制
        private void Connect_Click(object sender, EventArgs e)
        {
            try
            {
                if (!serialPort1.IsOpen)
                {
                    serialPort1.PortName = COM.Text;
                    serialPort1.BaudRate = int.Parse(BodeRate.Text);
                    Connect.Text = "断开";

                    serialPort1.Open();
                    COM.Enabled = false;
                    BodeRate.Enabled = false;

                }
                else if (serialPort1.IsOpen)
                {
                    _closing = true;

                    Connect.Text = "连接";
                    COM.Enabled = true;
                    BodeRate.Enabled = true;
                    serialPort1.Close();
                    // while (Listening) Application.DoEvents();
                    //打开时点击，则关闭串口                    
                    serialPort1.Close();
                    _closing = false;
                }
            }

            catch (System.Exception)
            {
                MessageBox.Show("请检查您的串口！");
                Connect.Text = "连接";
                COM.Enabled = true;
                BodeRate.Enabled = true;
                return;
            }
        }


        private void serialportcheck()
        {
            string[] ports = SerialPort.GetPortNames();// 得到PC的物理串口号
            Array.Sort(ports); // 按从小到大排序
            COM.Items.Clear();
            COM.Items.AddRange(ports); // 将所得到的串口号添加到组合框中以便进行选择
            COM.SelectedIndex = COM.Items.Count > 0 ? 0 : -1;// 默认串口号  
        }

        private int Getserialportcount()
        {
            string[] ports = SerialPort.GetPortNames();// 得到PC的物理串口号
            return ports.Length;
        }

        #endregion

        #region 串口刷新
        static int previousAvailableSerialPortNumbe = 0;  
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                int currentAvailableSerialPortNumber = Getserialportcount();
                if (previousAvailableSerialPortNumbe != currentAvailableSerialPortNumber)
                {
                    serialportcheck();
                    previousAvailableSerialPortNumbe = currentAvailableSerialPortNumber;
                }
            }
        }
        #endregion

        #region 数据发送
        private void Data_Send(List<byte> buff)
        {
            if (serialPort1.IsOpen)
            {
                byte[] a = new byte[] { 1, 21, 3, 1, 4 };
                serialPort1.Write(a, 0, 5);
                //serialPort1.Write(buff.ToArray(), 0, buff.Count);
            }
            else
            {
                MessageBox.Show(" 串口未打开！");
            }
        }
        #endregion

        #region 获取16进制数组list
        private List<byte> Get_HexBuffer(string input_string)
        {
            MatchCollection mc = Regex.Matches(input_string, @"(?i)[/da-f]{2}");
            List<byte> buf = new List<byte>();//填充到这个临时列表中  
            //依次添加到列表中  
            foreach (Match m in mc)
            {
                buf.Add(byte.Parse(m.Value));
            }
            string s = string.Join(",", buf.ToArray());           
            return buf;
        }

            
                
        #endregion

        #region 外观
        private void label1_MouseEnter(object sender, EventArgs e)
        {
            label1.BackColor = System.Drawing.Color.LightSlateGray;
        }

        private void label1_MouseLeave(object sender, EventArgs e)
        {
            label1.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
        }

        private void label4_MouseEnter(object sender, EventArgs e)
        {
            label4.BackColor = System.Drawing.Color.LightSlateGray;
        }

        private void label4_MouseLeave(object sender, EventArgs e)
        {
            label4.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
        }

        private void label5_MouseEnter(object sender, EventArgs e)
        {
            label5.BackColor = System.Drawing.Color.LightSlateGray;
        }

        private void label5_MouseLeave(object sender, EventArgs e)
        {
            label5.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
        }

        private void label6_Paint(object sender, PaintEventArgs e)
        {
            SolidBrush SegBrush;
            SegBrush = new SolidBrush(System.Drawing.Color.Gray);
            Pen pen = new Pen(SegBrush, 1);
            //e.Graphics.FillRectangle(SegBrush, RcTime);

            label6.BorderStyle = BorderStyle.None;

            pen.Color = Color.White;

            Rectangle myRectangle = new Rectangle(0, 0, label6.Width, label6.Height);
            ControlPaint.DrawBorder(e.Graphics, myRectangle, System.Drawing.Color.Gray, ButtonBorderStyle.Solid);//画个边框}

        }
        #endregion

        



    }
}
